package com.demo.gateway.sentinel.factory.impl;

import com.demo.gateway.sentinel.config.DynamicConfig;
import com.demo.gateway.sentinel.config.SysConstatnt;
import com.demo.gateway.sentinel.factory.FlowControl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TimesCountFlowControlImpl implements FlowControl {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DynamicConfig dynamicConfig;

    @Override
    public boolean control() {
        // 固定时间窗口流控简单实现
        // todo 高并发下的优化控制
        Integer cur = (Integer) redisTemplate.opsForValue().get(SysConstatnt.RedisKeyList.FLOWCOUNT_TIMECOUNTRATE);
        if(cur == null) {
            redisTemplate.opsForValue().set(SysConstatnt.RedisKeyList.FLOWCOUNT_TIMECOUNTRATE,0,1, TimeUnit.MINUTES);
        } else if(cur.intValue() < dynamicConfig.getFcRateTimeCount() ) {
            redisTemplate.opsForValue().increment(SysConstatnt.RedisKeyList.FLOWCOUNT_TIMECOUNTRATE);
        } else {
            // 到达最大值，进行流控
            return true;
        }
        return false;
    }

    @Override
    public String getName() {
        return "timescount";
    }
}
